﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace SharedLib.Helpers
{
    public class SecurityHelper
    {
        public static RSACryptoServiceProvider GetKeyInContainer(string ContainerName)
        {
            // Create the CspParameters object and set the key container 
            // name used to store the RSA key pair.
            CspParameters cp = new CspParameters();
            cp.KeyContainerName = ContainerName;

            // Create a new instance of RSACryptoServiceProvider that accesses
            // the key container MyKeyContainerName.
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
            return rsa;
        }

        public static void DeleteKeyFromContainer(string ContainerName)
        {
            // Create the CspParameters object and set the key container 
            // name used to store the RSA key pair.
            CspParameters cp = new CspParameters();
            cp.KeyContainerName = ContainerName;

            // Create a new instance of RSACryptoServiceProvider that accesses
            // the key container.
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

            // Delete the key entry in the container.
            rsa.PersistKeyInCsp = false;

            // Call Clear to release resources and delete the key from the container.
            rsa.Clear();
        }

        public static string EncryptString(string str, string rsaContainer)
        {
            if (String.IsNullOrEmpty(str)) return str;
            var key = SharedLib.Helpers.SecurityHelper.GetKeyInContainer(rsaContainer);
            var bytes = key.Encrypt(System.Text.ASCIIEncoding.Default.GetBytes(str), true);
            return Convert.ToBase64String(bytes);
        }

        public static string DecryptString(string str, string rsaContainer)
        {
            if (String.IsNullOrEmpty(str)) return str;
            var key = SharedLib.Helpers.SecurityHelper.GetKeyInContainer(rsaContainer);
            var bytes = Convert.FromBase64String(str);
            return System.Text.ASCIIEncoding.Default.GetString(key.Decrypt(bytes, true));
        }
    }
}
